package com.study.util.treeutil;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 就是树节点属性在返回前端时要能够支持自定义属性名
 */
/**
 * 树构建
 * 
 * @author chenk
 *
 */
public class TreeUtil_4_0 {

	/**
	 * 新增的属性转换方法
	 * 
	 * @author chenk
	 *
	 * @param <T>
	 * @param <TreeNode>
	 */
	public interface Convert<T, TreeNodeMap> {
		public void convert(T t, TreeNodeMap treeNode);
	}

	/**
	 * 递归调用转换
	 * 
	 * @param <T>
	 * 
	 * @param <T>
	 * @param menuEntityList
	 * @param parentId
	 * @param convert
	 * @return
	 */
	public static <T> List<TreeNodeMap> build(List<T> list, Object parentId, TreeNodeConfig treeNodeConfig,
			Convert<T, TreeNodeMap> convert) {

		// 原来调用方法做的事情
		List<TreeNodeMap> treeNodes = new ArrayList<>();
		for (T obj : list) {
			TreeNodeMap treeNode = new TreeNodeMap(treeNodeConfig);

			convert.convert(obj, treeNode);
			treeNodes.add(treeNode);
		}

		List<TreeNodeMap> finalTreeNodes = new ArrayList<>();
		for (TreeNodeMap treeNode : treeNodes) {
			if (parentId.equals(treeNode.getParentId())) {
				finalTreeNodes.add(treeNode);
				innerBuild(treeNodes, treeNode);
			}
		}

		return finalTreeNodes;

	}

	private static void innerBuild(List<TreeNodeMap> treeNodes, TreeNodeMap parentNode) {
		for (TreeNodeMap childNode : treeNodes) {
			if (parentNode.getId().equals(childNode.getParentId())) {
				List<TreeNodeMap> children = parentNode.getChildren();
				if (children == null) {
					children = new ArrayList<>();
					parentNode.setChildren(children);
					childNode.setParentId(parentNode.getId());
				}
				children.add(childNode);
				childNode.setParentId(parentNode.getId());
				innerBuild(treeNodes, childNode);
			}
		}
	}

	public static void main(String[] args) throws JsonProcessingException {
		TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
		// 自定义属性名
		treeNodeConfig.setCodeKey("number");

		// 1.模拟菜单数据
		List<MenuEntity> list = new ArrayList<>();
		list.add(new MenuEntity("1", "0", "系统管理", "sys", "/sys"));
		list.add(new MenuEntity("11", "1", "用户管理", "user", "/sys/user"));
		list.add(new MenuEntity("111", "11", "用户添加", "userAdd", "/sys/user/add"));
		list.add(new MenuEntity("2", "0", "店铺管理", "store", "/store"));
		list.add(new MenuEntity("21", "2", "商品管理", "shop", "/shop"));

		// 2.MenuEntity->TreeNode
		List<TreeNodeMap> treeNodes = TreeUtil_4_0.build(list, "0", treeNodeConfig,
				new Convert<MenuEntity, TreeNodeMap>() {

					@Override
					public void convert(MenuEntity menuEntity, TreeNodeMap treeNode) {
						treeNode.setId(menuEntity.getId());
						treeNode.setParentId(menuEntity.getPid());
						treeNode.setCode(menuEntity.getCode());
						treeNode.setName(menuEntity.getName());

						// 扩展属性
						treeNode.extra("extra1", "123");
					}
				});

		// 3.返回
		ObjectMapper om = new ObjectMapper();
		String result = om.writeValueAsString(treeNodes);
		System.out.println(result);
	}
}
